#!/bin/sh

# manage miniupnpd and minissdpd, the IGD/NAT-DMP daemons

# this script must be restarted ($0 restart) if the wan address or interface changes
# this script should be run before catawampus (S85catawampus) since catawampus may restart it
# if /tmp/upnpd-enabled is not present, it will be a no-op (catawampus manages that file)
# dhclient-script runs restart upnpd

enabler=/tmp/upnpd-enabled

start()
{
  if [ ! -f "$enabler" ]; then
    echo "$enabler does not exist, refusing to start."
    return
  fi
  if [ ! -s /config/upnp.uuid ]; then
    uuidgen >/config/upnp.uuid
  fi
  uuid=$(cat /config/upnp.uuid)

  sn=$(serial)
  model=$(cat /etc/platform)

  if [ -e /config/nickname ]; then
    friendly=$(cat /config/nickname)
  else
    friendly=$(uname -n)
  fi

  lanipv4=$(ip -4 -o addr show br0)
  lanipv4=${lanipv4#* inet }
  lanipv4=${lanipv4%%/*}

  version="Google Fiber $(cat /etc/version) UPnP/1.1 MiniUPnPd"

  wan=$(activewan)

  if [ -z "$wan" ]; then
    echo "no wan interface is active, refusing to start."
    return
  fi

  set -- \
      miniupnpd -i "$wan" -a "$lanipv4" -u "$uuid" \
          -s "$sn" -m "$model" -z "$friendly" -N -d -V "$version"
  echo "Running:" "$@"
  babysit 10 "$@" 2>&1 | logos upnpd &
}

stop()
{
  killpid /var/run/miniupnpd.pid
  iptables -F MINIUPNPD
}


case "$1" in
  start)
    start
    ;;
  stop)
    stop
    ;;
  restart)
    stop
    start
    ;;
  isrunning)
    if [ -f /var/run/miniupnpd.pid ]; then
      exit 0
    else
      exit 1
    fi
    ;;
  *)
    echo "Usage: $0 {start|stop|restart|isrunning}"
    exit 1
    ;;
esac

exit 0
